package Concurrency2.Chapter03_CAS_Atomic;

import sun.misc.Unsafe;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * Instruction：通过CAS修改属性的值
 * Author：@author MaLi
 */
public class T01_Unsafe {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
        /*Unsafe unsafe = Unsafe.getUnsafe();
        System.out.println(unsafe);*/

        /*Constructor<Unsafe> constructor = Unsafe.class.getConstructor();
        constructor.setAccessible(true);
        Unsafe unsafe = constructor.newInstance();
        System.out.println(unsafe);*/

        Unsafe theUnsafe = getTheUnsafe();
        //使用Unsafe修改内存中的对象
        Some some = new Some();
        some.setId(1);
        some.setName("Mark");
        boolean result = theUnsafe.compareAndSwapObject(some, theUnsafe.objectFieldOffset(Some.class.getDeclaredField("id")), 1, 2);

        //针对静态属性的修改, 应该修改的是Some.class这个"类"对象
        //result = theUnsafe.compareAndSwapObject(Some.class, theUnsafe.staticFieldOffset(Some.class.getDeclaredField("flag")), true, false);

        System.out.println(result);
        System.out.println(some);
    }

    private static Unsafe getTheUnsafe() throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        return (Unsafe) theUnsafe.get(null);
    }

    static class Some{
        private static Boolean flag = true;
        private Integer id;
        private String name;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public static Boolean getFlag() {
            return flag;
        }

        public static void setFlag(Boolean flag) {
            Some.flag = flag;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Some{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}'+flag;
        }
    }
}
